/**
 * Promise 静态方法
 
Promise.all()
Promise.race()
 */
/* let p1 = Promise.resolve('success')
console.log(p1)
p1.then(res => {
  console.log(res)
})

let p2 = Promise.reject('fail')
console.log(p2)
p2.catch(res => {
  console.log(res)
}) */

function foo(flag) {
  if(flag) {
    return new Promise(resolve => {
      resolve('foo success')
    })
  } else {
    // return 'fail'   // 会报错
    return Promise.reject('foo fail')
  }
}

foo(false).then(res => {
  console.log(res)
},err => {
  console.log(err)
})


let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(1)
    resolve(11)
  }, 1000)
})

let p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(2)
    resolve(22)
    // reject('2 fail')
  }, 2000)
})

let p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(3)
    resolve(33)
  }, 3000)
})

// 三个异步操作全部执行完毕, 只要有一个失败 全部失败
/* Promise.all([p1, p2, p3]).then(res => {
  console.log('all', res)
}, err => {
  console.log(err)
}) */

// 只要有一个完成 则认为完成 , 只要有一个失败 全部失败
Promise.race([p1, p2, p3]).then(res => {
  console.log('all', res)
}, err => {
  console.log(err)
})


/**
 * 应用场景1
 */
const imgArr = ['a.jpg', 'b.jpg']
let promiseArr = []
imgArr.forEach(item => {
  promiseArr.push(new Promise((resolve, reject)=> {
    // 图片上传操作
    resolve('img upload')
  }))
})

Promise.all(promiseArr).then(res => {
  console.log('all upload', res)
}, err => {
  console.log(err)
})


/**
 * 应用场景 2 ： 图片加载超时
 */
function getImg(params) {
  return new Promise((resolve, reject)=> {
    // 图片上传操作
    let img = new Image()
    img.onload = function(){
      resolve(img)
    }
    img.src = 'https://www.imooc.com/static/img/index/logo2020.png'
  })
  
}

function timeout(){
  return new Promise((resolve, reject)=> {
    setTimeout(() => {
      reject('upload fail')
    }, 2000)
  })
}

Promise.race([getImg(), timeout()]).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})